package nccloud.web.erm.util.expenseaccount;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import nc.itf.uap.IUAPQueryBS;
import nc.jdbc.framework.processor.ArrayListProcessor;
import nc.nccloud.util.erm.expenseaccount.Func;
import nc.vo.ep.bx.BXBusItemVO;
import nc.vo.er.exception.ExceptionHandler;
import nc.vo.ml.NCLangRes4VoTransl;
import nc.vo.platform.appsystemplate.AreaVO;
import nc.vo.platform.appsystemplate.FormPropertyVO;
import nc.vo.platform.appsystemplate.PageTempletVO;
import nc.vo.pub.BusinessException;
import nc.vo.pub.lang.UFDate;
import nc.web.pub.erm.utils.ExchangeRateUtil;
import nccloud.framework.service.ServiceLocator;
import nccloud.framework.service.meta.vometa.AttributeMeta;
import nccloud.framework.web.convert.pattern.GridConvertor;
import nccloud.framework.web.ui.conver.MetaPathFinder;
import nccloud.framework.web.ui.pattern.extbillcard.ExtBillCard;
import nccloud.framework.web.ui.pattern.form.Form;
import nccloud.framework.web.ui.pattern.grid.Grid;
import nccloud.pubitf.erm.expenseaccount.jkbx.IExpenseaccountService;
import nccloud.pubitf.platform.template.IPageTemplet;

public class KKExpenseaccountMainUtil {

	public static Grid getGrid(InputStream in, ExtBillCard extbillcard) throws BusinessException {
		Workbook wb = null;
		BXBusItemVO[] vo = null;
		try {
			wb = new XSSFWorkbook(in);
			Sheet sheet = wb.getSheetAt(0);
			org.apache.poi.ss.usermodel.Row row = sheet.getRow(0);
			if ((null == row) || (0 == row.getLastCellNum())) {
				throw new BusinessException(
						NCLangRes4VoTransl.getNCLangRes().getStrByID("ersetting_2", "22011rr-000074"),
						NCLangRes4VoTransl.getNCLangRes().getStrByID("common", "UPP2011-000380"));
			}

			JSONArray arr = JSON.parseArray(extbillcard.getUserjson());
			CopyOnWriteArrayList headitem = new CopyOnWriteArrayList();
			for (int count = 0; count < row.getLastCellNum(); count++) {
				org.apache.poi.ss.usermodel.Cell title = row.getCell(count);
				if (null != title) {
					for (int i = 0; i < arr.size(); i++) {
						JSONObject obj = arr.getJSONObject(i);
						if ((title.getStringCellValue().equals(obj.getString("label")))
								&& ("true".equals(obj.getString("visible"))))
							headitem.add(obj);
					}
				}
			}
			PageTempletVO btvo = ((IPageTemplet) ServiceLocator.find(IPageTemplet.class))
					.getTempletVOWithCache(extbillcard.getTempletid());

			String refName = "";
			String baseSql = "select id from md_class where refmodelname = ";
			IUAPQueryBS iuapQryService = (IUAPQueryBS) ServiceLocator.find(IUAPQueryBS.class);
			for (AreaVO bodyarea : btvo.getAreaList()) {
				if ("arap_bxbusitem".equals(bodyarea.getCode())) {
					for (int j = 0; j < bodyarea.getFormPropertyList().size(); j++) {
						FormPropertyVO formvo = (FormPropertyVO) bodyarea.getFormPropertyList().get(j);

						for (int i = 0; i < arr.size(); i++) {
							JSONObject obj = arr.getJSONObject(i);
							if (formvo.getCode().equals(obj.getString("key"))) {
								MetaPathFinder m = new MetaPathFinder(bodyarea.getMetaspace(), formvo.getMetapath());
								AttributeMeta meta = (AttributeMeta) m.getCurrentAttribute();

								if (formvo.getCode().startsWith("defitem")) {
									if ("refer".equalsIgnoreCase(formvo.getItemtype())) {
										refName = formvo.getRefname();

										String refSql = baseSql + "'" + refName + "' or displayname = '" + refName
												+ "'";
										List mdIdList = (List) iuapQryService.executeQuery(refSql,
												new ArrayListProcessor());
										if ((mdIdList != null) && (mdIdList.size() > 0)) {
											Object[] objects = (Object[]) mdIdList.get(0);
											obj.put("mdid", objects[0]);
										}
									} else if ("31".equalsIgnoreCase(formvo.getDatatype().toString())) {
										obj.put("mdid", "BS000010000100001031");
									} else if ("52".equalsIgnoreCase(formvo.getDatatype().toString())) {
										obj.put("mdid", "BS000010000100001052");
									} else if ("1".equalsIgnoreCase(formvo.getDatatype().toString())) {
										obj.put("mdid", "BS000010000100001001");
									} else if ("56".equalsIgnoreCase(formvo.getDatatype().toString())) {
										obj.put("mdid", "BS000010000100001056");
									}

									obj.put("datatype", formvo.getDatatype());
								} else {
									obj.put("mdid", meta.getEntity().getDatatype());
									obj.put("datatype", formvo.getDatatype());
								}
							}
						}
					}
				}
			}

			if ((headitem == null) || (headitem.size() == 0)) {
				throw new BusinessException(
						NCLangRes4VoTransl.getNCLangRes().getStrByID("ersetting_2", "22011rr-000074"),
						NCLangRes4VoTransl.getNCLangRes().getStrByID("common", "UPP2011-000380"));
			}

			vo = ((IExpenseaccountService) ServiceLocator.find(IExpenseaccountService.class)).converXlsToBusitemVO(
					sheet, headitem,
					extbillcard.getHead().getModel().getRows()[0].getCell("pk_org").getValue().toString(), false);

			Form form = extbillcard.getHead();
			UFDate djrq = new UFDate(ERMDataTableUtil.getHeadValue(form, "djrq").toString());
			Integer paytarget = Integer
					.valueOf(Integer.parseInt(ERMDataTableUtil.getHeadValue(form, "paytarget").toString()));
			for (BXBusItemVO bodyvo : vo) {
				for (int i = 0; i < arr.size(); i++) {
					JSONObject obj = arr.getJSONObject(i);
					if ((bodyvo.getAttributeValue(obj.getString("key")) == null)
							&& (!obj.getString("initialvalue").equals(""))
							&& (obj.getString("visible").equals("false"))) {
						bodyvo.setAttributeValue(obj.getString("key"), obj.getString("initialvalue"));
					}
				}
//				ERMBillVOUtil.dealOneBodyHbbmAndCustomer(djrq, paytarget, bodyvo);
			}
			Grid grid = new Grid();
			grid.setTempletid(extbillcard.getTempletid());
			grid.setPageid(extbillcard.getPageid());
			GridConvertor gc = new GridConvertor();
			grid = gc.toGrid("arap_bxbusitem", vo);
			return grid;
		} catch (IOException | BusinessException e) {
			throw new BusinessException(e);
		} finally {
			try {
				in.close();
			} catch (IOException e) {
				ExceptionHandler.consume(e);
			}
		}
	}

	public static void dealZzhllxForPrint(ExtBillCard extbillcard) {
		Grid[] allBodys = extbillcard.getAllBodys();
		try {
			for (Grid grid : allBodys)
				for (int i = 0; i < grid.getModel().getRows().length; i++) {
					nccloud.framework.web.ui.model.row.Row row = grid.getModel().getRows()[i];
					String hllx = Func.toString(ERMDataTableUtil.getBodyValueByRow(row, "zzhllx"));

					if (!ExchangeRateUtil.checkZzhllx(hllx))
						ERMDataTableUtil.setBodyValueByRow(row, "zzhllx", null);
				}
		} catch (Exception e) {
			ExceptionHandler.consume(e);
		}
	}

}